#pragma once

/**
 * LoopThreadLoop:对所有的LoopThread进行管理及分配
 * 在服务器中，主从Reactor模型是主线程只负责新连接获取，
 * 从属线程负责新连接的事件监控及处理因此当前的线程池，有可能从属线程会数量为0，也就是实现单Reactor服务器，
 * 一个线程既负责获取新连接负责连接的处理
 */

#include "EventLoop.hpp"
#include "Logger.h"

#include <vector>

namespace devem {
class LoopThreadPool {
public:
    LoopThreadPool(EventLoop* main_thread) : base_loop_(main_thread), thread_num_(0), next_(0) {}

    void SetThreadNum(const int num) { thread_num_ = num; }

    void start() {
        threads_.resize(thread_num_);
        loops_.resize(thread_num_);
        for (int i = 0; i < thread_num_; i++) {
            LoopThread* thread = new LoopThread();
            // Use unique_ptr automatically delete LoopThread
            threads_[i] = std::unique_ptr<LoopThread>(thread);
            loops_[i] = thread->SelfEventLoop();
        }
    }

    EventLoop* GetNextLoop() {
        if (thread_num_ == 0) {
            // 分配给主线程
            return base_loop_;
        } else {
            // 轮询分配
            next_ = (next_ + 1) % thread_num_;
            return loops_[next_];
        }
    }

private:
    int thread_num_;  // 从属线程数量
    EventLoop* base_loop_;
    std::vector<std::unique_ptr<LoopThread>> threads_;
    std::vector<EventLoop*> loops_;
    int next_;
};

}  // namespace devem